package com.c6906.vdam.monitor.mapper;

import com.c6906.vdam.monitor.model.CpuUsage;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface CpuUsageMapper {
    @Insert("INSERT INTO cpu_usage(server_id,msg_serial, host_name, cpu_id, event_time, usage_percent, created_at, updated_at) " +
            "VALUES(#{serverId},#{msgSerial}, #{hostName}, #{cpuId}, #{eventTime}, #{usagePercent}, #{createdAt}, #{updatedAt})")
    void insertCpuUsage(CpuUsage cpuUsage);

    @Select("SELECT * FROM cpu_usage WHERE server_id = #{serverId}")
    List<CpuUsage> findByServerId(Long serverId);

    @Select("SELECT \n" +
            "    t1.HOST_NAME as hostName, \n" +
            "    t1.CPU_ID as cpuId, \n" +
            "    t1.EVENT_TIME as eventTime, \n" +
            "    t1.USAGE_PERCENT as usagePercent ,\n" +
            "  t1.CREATED_AT as createdAt ,\n" +
            "  t1.UPDATED_AT as updatedAt  " +
            "FROM \n" +
            "    VDAM2024.CPU_USAGE t1\n" +
            "JOIN \n" +
            "    (\n" +
            "        SELECT \n" +
            "            HOST_NAME, \n" +
            "            CPU_ID, \n" +
            "            MAX(EVENT_TIME) AS LAST_EVENT_TIME\n" +
            "        FROM \n" +
            "            VDAM2024.CPU_USAGE\n" +
            "        GROUP BY \n" +
            "            HOST_NAME, \n" +
            "            CPU_ID\n" +
            "    ) t2 \n" +
            "ON \n" +
            "    t1.HOST_NAME = t2.HOST_NAME \n" +
            "    AND t1.CPU_ID = t2.CPU_ID \n" +
            "    AND t1.EVENT_TIME = t2.LAST_EVENT_TIME;")
    List<CpuUsage> findLastCpuUsage();

}
